package com.example.websocketserver.configuration;

import com.alibaba.fastjson.JSON;
import com.example.websocketserver.pojo.WebsocketRealMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WebsocketPushService {

    private final SimpMessagingTemplate messagingTemplate;

    /**
     * topic广播消息推送
     *
     * @param topic   主题
     * @param message 消息完整体
     */
    public void push2Topic(String topic, WebsocketRealMessage message) throws JsonProcessingException {
        messagingTemplate.convertAndSend(topic, new ObjectMapper().writeValueAsString(message));
        log.info("主动推送消息:{}", JSON.toJSONString(message));
    }

    /**
     * 单点推送
     *
     * @param userId  用户ID
     * @param queue   队列
     * @param message 用户级别的消息
     */
    public void push2User(String userId, String queue, WebsocketRealMessage message) throws JsonProcessingException {
        // 客户端订阅：/user/queue/message
        // 服务器推送指定用户：/user/u_用户id/queue/message
        messagingTemplate.convertAndSendToUser(userId, queue, new ObjectMapper().writeValueAsString(message));
    }
}
